package com.zg.api.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zg.api.domain.req.ApiInfoPageReq;
import com.zg.api.domain.vo.ApiInfoVo;
import com.zg.api.service.ApiInfoService;
import com.zg.api.sys.ApiE;
import com.zg.common.core.dao.IDao;
import com.zg.common.core.dao.apis.entity.ApiInfo;
import com.zg.common.core.dao.apis.ApiInfoDao;
import com.zg.common.core.service.PageBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/6/16 20:11
 */

@Slf4j
@Service
public class ApiInfoServiceImpl extends PageBaseService<ApiInfo,ApiInfoDao> implements ApiInfoService {


//    @Autowired
//    @Qualifier("apiInfoDao")
//    @Override
//    protected void setDao(IDao<ApiInfo> dao) {
//        this.dao = dao;
//    }

    @Override
    public Page<ApiInfoVo> pageInfo(ApiInfoPageReq req, Class<ApiInfoVo> voClass) {
        Page<ApiInfo> page = new Page<>(req.getPage(), req.getPageSize());
        LambdaQueryWrapper<ApiInfo> qw = buildPageQueryWrapper(req);
        Page<ApiInfo> pageInfo = baseDao.pageInfo(page, qw);

        List<ApiInfoVo> voList = pageInfo.getRecords().stream()
                .map(entity -> convertToVo(entity, voClass))
                .collect(Collectors.toList());

        Page<ApiInfoVo> voPage = new Page<>(pageInfo.getCurrent(), pageInfo.getSize(), pageInfo.getTotal());
        voPage.setRecords(voList);

        return voPage;
    }

    public  LambdaQueryWrapper<ApiInfo> buildQueryWrapper(ApiInfo info){
        LambdaQueryWrapper<ApiInfo> qw = new LambdaQueryWrapper<>();
        qw.like(!StrUtil.isEmpty(info.getApiName()), ApiInfo::getApiName, info.getApiName());
        qw.eq(!StrUtil.isEmpty(info.getApiCode()), ApiInfo::getApiCode, info.getApiCode());
        return qw;
    }


    public ApiInfo getByCode(String name){
        LambdaQueryWrapper<ApiInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(ApiInfo::getApiCode,name);
        return baseDao.getOne(qw);
    }

    @Override
    protected void preAdd(ApiInfo source) {
        ApiInfo info= getByCode(source.getApiCode());
        if(info!=null){
            ApiE.API_CODE_IS_EXIST.happen();
        }
    }
}
